package com.okbihuo.perm.core.auth.handler;

import cn.hutool.extra.servlet.ServletUtil;
import com.okbihuo.perm.core.auth.domain.BaseAuthUser;
import com.okbihuo.perm.core.auth.jwt.JwtHelper;
import com.okbihuo.perm.core.auth.jwt.JwtTokenInfo;
import com.okbihuo.perm.core.logger.publisher.LogPublisher;
import com.okbihuo.perm.core.tool.api.R;
import com.okbihuo.perm.core.tool.jackson.JsonUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@Component
@RequiredArgsConstructor
public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        BaseAuthUser userDetails = (BaseAuthUser)authentication.getPrincipal();
        Date expiration = new Date(System.currentTimeMillis() + JwtHelper.EXPIRES);
        // 生成jwt-token
        String token = JwtHelper.generateToken(userDetails);
        // 构造返回结构
        JwtTokenInfo jwtTokenInfo = JwtTokenInfo.builder()
                .token(token)
                .expires(expiration.getTime())
                // 减去一秒已消除传输误差
                .duration(JwtHelper.EXPIRES-1000)
                .build();
        // 构造统一返回结构
        R<JwtTokenInfo> success = R.data(jwtTokenInfo, "登录成功");
        LogPublisher.info("登录成功", jwtTokenInfo.toString());
        ServletUtil.write(response, JsonUtil.toJson(success), "application/json;charset=UTF-8");
    }
}
